// utils/websocketMessages.js
// WebSocket消息格式配置

/**
 * 语音对讲相关消息格式
 */
export const INTERCOM_MESSAGES = {
  // 发起语音对讲
  START: {
    type: 'SEND_AUDIO_AND_VIDEO_REQUEST',
    body: {
      toUser: '1',
      nickname: uni.getStorageSync('deviceNo'),
      msgId: 'uuid',
      content: '发起语音对讲',
      code: 100
    }
  },

  // 挂断语音对讲
  HANGUP: {
    type: 'SEND_AUDIO_AND_VIDEO_REQUEST',
    body: {
      toUser: uni.getStorageSync('deviceNo'),
      msgId: 'uuid',
      content: '挂断语音对讲',
      code: 102
    }
  },

  // 应用退出通知
  EXIT: {
    type: 'USER_EXIT_NOTICE_REQUEST',
    body: {
      nickname: uni.getStorageSync('deviceNo')
    }
  }
};

/**
 * 创建消息的工厂函数
 * @param {string} messageType 消息类型
 * @param {object} customData 自定义数据
 * @returns {object} 消息对象
 */
export function createMessage(messageType, customData = {}) {
  const baseMessage = INTERCOM_MESSAGES[messageType];
  if (!baseMessage) {
    throw new Error(`未知的消息类型: ${messageType}`);
  }

  // 生成唯一的msgId
  const msgId = generateUUID();

  return {
    ...baseMessage,
    body: {
      ...baseMessage.body,
      ...customData,
      msgId: msgId
    }
  };
}

/**
 * 生成UUID
 * @returns {string} UUID字符串
 */
function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

/**
 * 更新消息中的用户ID
 * @param {string} userId 用户ID
 */
export function updateUserId(userId) {
  Object.keys(INTERCOM_MESSAGES).forEach(key => {
    INTERCOM_MESSAGES[key].body.toUser = userId;
  });
}

export default INTERCOM_MESSAGES;